import router from "./router";
import { ElMessage, ElMessageBox } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, setToken, getUserId, setUserId } from "@/utils/auth";
import { getloginToken } from "@/api/login";
import { isRelogin } from "@/utils/request";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";

NProgress.configure({ showSpinner: false });

// 路由白名单
const whiteList = ["/login", "/register", "/forgotPassword", "/auth-redirect", "/bind"];
// 前置守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  // 在免登录白名单，直接进入
  if (whiteList.indexOf(to.path) !== -1) {
    next();
    return;
  }
  // 对接单点，根据票据获取token
  if (to.query.cssSsoTicket) {
    const cssSsoTicket = to.query.cssSsoTicket;
    await getloginToken(cssSsoTicket).then((res) => {
      if (res && res.code == 200) {
        console.log(res.token);
        setToken(res.token);
        setUserId(res.userId);
      }
    }).catch(err => {
      ElMessageBox.confirm('获取token失败，是否跳转登录页？', '系统提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }) .then(() => {
        next(to.href.replace(/\?cssSsoTicket=.*/gi, ''));
      })
    });
  }
  console.log(getToken(), "");
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title);
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        const user = await useUserStore().getInfo(getUserId()).then(async (data) => {
          isRelogin.show = false;
          return data;
        }).catch((err) => {
          ElMessageBox.confirm('获取用户信息失败，是否重新校验登录状态？', '系统提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }) .then(() => {
            // 校验登录状态，若未登录则跳转登录页
            checkLoginStatus();
            // 退出登录
            // loginOut();
          })
        });
        const menus = await usePermissionStore().generateRoutes(getUserId()).then((routes) => {
          return routes;
        }).catch(err => {
          console.log(err.message||"获取用户菜单失败！");
        });
        // 通过菜单接口获取菜单失败，取用户信息中的菜单
        if(!menus && user.extend1) {
          let menuList = [];
          try {
            menuList = JSON.parse(user.extend1);
          } catch (error) {
            menuList = [];
          }
          // 菜单转路由
          usePermissionStore().menuToRoutes(menuList);
        }
        // hack方法 确保addRoutes已完成
        next({ ...to, replace: true });
      } else {
        next();
      }
    }
  } else {
    // 校验登录状态，若未登录则跳转登录页
    checkLoginStatus();
    // next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    NProgress.done()
  }
});

// 后置守卫
router.afterEach(() => {
  NProgress.done();
});

// 校验登录状态，若未登录则跳转登录页
function checkLoginStatus() {
  // const env = import.meta.env.VITE_APP_ENV;
  // 开发环境前端校验登录状态，其它环境通过后端校验登录状态
  // if(env == "development") {
  //   // 跳转单点登录页并检测是否登录
  //   location.href = import.meta.env.VITE_APP_SSO_SERVICE + '/quit.action?toUrl=' + location.href
  // } else {
    // 跳转登录页面，通过后端校验实现跳转
    location.href = import.meta.env.VITE_APP_PORTAL_SERVICE;
  // }
}

// 退出登录
function loginOut() {
  useUserStore().logOut().then((res) => {
    ElMessage.error(err);
    console.log(res);
    location.href = res.retUrl;
  })
}